package com.dense.kuiniu.bookborrow.business.home.renew;

import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.TextView;

import com.blankj.utilcode.util.LanguageUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.dense.kuiniu.bookborrow.R;
import com.dense.kuiniu.bookborrow.base.BaseFragment;
import com.dense.kuiniu.bookborrow.base.Url;
import com.dense.kuiniu.bookborrow.business.adapter.BookRenewAdapter;
import com.dense.kuiniu.bookborrow.business.entity.BorrowBookInfo;
import com.dense.kuiniu.bookborrow.business.entity.BorrowResult;
import com.dense.kuiniu.bookborrow.business.entity.ReaderInfo;
import com.dense.kuiniu.bookborrow.receiver.SystemTTS;
import com.dense.kuiniu.bookborrow.view.CountDownView;
import com.dense.kuiniu.bookborrow.view.CounterController;
import com.dense.kuiniu.bookborrow.view.SpaceItemDecoration;
import com.dense.kuiniu.bookborrow.view.dialog.CommonDialog;
import com.dense.kuiniu.bookborrow.xjSetting.config.ShareKeyConfig;
import com.dense.kuiniu.bookborrow.xjSetting.utils.SharePreferceUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.rxjava.rxlife.RxLife;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.rxjava3.functions.Consumer;
import rxhttp.RxHttp;

/**
 * @author Administrator
 * @date 2020/8/13
 */
public class RenewBookDelegate extends BaseFragment {
    private static final String CARD = "reader";
    private static final String BOOK_LIST = "bookList";

    public static RenewBookDelegate getInstance(String cardNo, ArrayList<BorrowBookInfo> bookList) {
        Bundle bundle = new Bundle();
        bundle.putString(CARD, cardNo);
        bundle.putParcelableArrayList(BOOK_LIST, bookList);
        RenewBookDelegate delegate = new RenewBookDelegate();
        delegate.setArguments(bundle);
        return delegate;
    }

    @BindView(R.id.recycler_view)
    RecyclerView mRecyclerView;
    @BindView(R.id.tv_title)
    TextView mTvTitle;
    @BindView(R.id.count_down_view)
    CountDownView mCountDownView;
    @BindView(R.id.tv_choose_count)
    TextView mTvChooseCount;
    @BindView(R.id.cb_all)
    CheckBox mCbAll;
    @BindView(R.id.tv_renew_book)
    TextView mTvRenewBook;
    @BindView(R.id.tv_name)
    TextView mTvName;
    @BindView(R.id.tv_card)
    TextView mTvCard;
    @BindView(R.id.tv_can_borrow_count)
    TextView mTvBorrowCount;

    @BindView(R.id.tv_state)
    TextView mTvState;
    private BookRenewAdapter mBookRenewAdapter;
    private Map<String, BorrowBookInfo> mSelectedMap = new ConcurrentHashMap<>();
    private CommonDialog mDialog;
    private String mCardNo;
    private ArrayList<BorrowBookInfo> mBookList;
    private CountDownLatch mDownLatch;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = getArguments();
        if (bundle != null) {
            mCardNo = bundle.getString(CARD);
            mBookList = bundle.getParcelableArrayList(BOOK_LIST);
        }
    }

    @Override
    protected int getLayoutRes() {
        return R.layout.delegate_renew_book;
    }

    @Override
    protected void init() {
        if (getActivity() != null) {

//                if (info != null) {
//                    mTvName.setText(String.format("%s%s", getString(R.string.text_user_name), info.getUserName()));
//                    mTvCard.setText(String.format("%s%s", getString(R.string.text_card_no), info.getAccount()));
//                    mTvBorrowCount.setText(String.format(LanguageUtils.getCurrentLocale(),
//                            "%s%d", getString(R.string.text_can_borrow_number),
//                            info.getBorrowBookCount()));
//                    mTvPeriodicalCount.setText(String.format(LanguageUtils.getCurrentLocale(),
//                            "%s%d", getString(R.string.text_can_borrow_periodical_count),
//                            info.getBorrowPeriodicalCount()));
//                    mTvState.setText(String.format("%s%s", getString(R.string.text_state), info.getState()));
//                }
            queryReaderInfo();
            mTvTitle.setText(R.string.text_book_renew);
            mRecyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 2));
            mRecyclerView.setAdapter(mBookRenewAdapter = new BookRenewAdapter(R.layout.item_book_renew, null));
            mRecyclerView.addItemDecoration(new SpaceItemDecoration(20));
            mBookRenewAdapter.addChildClickViewIds(R.id.checkbox);
            mBookRenewAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
                @Override
                public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
                    BorrowBookInfo bookBean = (BorrowBookInfo) adapter.getItem(position);
                    CheckBox checkBox = (CheckBox) view;
                    if (bookBean != null) {
                        if (checkBox.isChecked()) {
                            mSelectedMap.put(bookBean.getBarCode(), bookBean);
                        } else {
                            mSelectedMap.remove(bookBean.getBarCode());
                        }
                        checkIsAll();
                    }
                }
            });
            mBookRenewAdapter.setEmptyView(R.layout.view_loading);
            int second = SharePreferceUtil.getInstance(getContext()).getInt(ShareKeyConfig.ER_JI_CAIDAN,60);
            mCountDownView.setSeconds(second);
            mCountDownView.start(new CounterController.OnCompleteListener() {
                @Override
                public void onComplete() {
                    exit();
                }
            });
            mTvChooseCount.setText(String.format(LanguageUtils.getCurrentLocale(),
                    "%s%d%s", getString(R.string.text_had_choose), mSelectedMap.size(), getString(R.string.text_book_unit)));
            mCbAll.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    checkAll(mCbAll.isChecked());
                }
            });

        }

    }

    private void queryReaderInfo() {
        RxHttp.get("cslinks/rest/getReaderinforAll")
                .add("ReaderBarcode", mCardNo)
                .asString()
                .to(RxLife.toMain(this))
                .subscribe(new Consumer<String>() {
                    @Override
                    public void accept(String s) throws Throwable {
                        Gson gson = new Gson();
                        ArrayList<ReaderInfo> list = gson.fromJson(s, new TypeToken<ArrayList<ReaderInfo>>() {
                        }.getType());
                        if (list != null && !list.isEmpty()) {
                            setReaderInfo(list.get(0));
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Throwable {

                    }
                });
    }

    private void setReaderInfo(ReaderInfo info) {
        mTvName.setText(String.format("%s%s", getString(R.string.text_user_name), info.getName()));
        mTvCard.setText(String.format("%s%s", getString(R.string.text_card_no), info.getReaderCode()));
        mTvBorrowCount.setText(String.format(LanguageUtils.getCurrentLocale(),
                "%s%s", "已借数量：",
                info.getBorrowCount()));
        mTvState.setText(String.format("%s%s", getString(R.string.text_state), info.getState()));
    }


    @OnClick({R.id.tv_renew_book, R.id.tv_return})
    public void onClick(View view) {
        super.onClick(view);
    }

    @Override
    protected void onClick2(View view) {
        int id = view.getId();
        switch (id) {
            case R.id.tv_return:
                exit();
                break;
            case R.id.tv_renew_book:
                showRenew();
                break;
        }
    }

    @Override
    public void onSupportVisible() {
        super.onSupportVisible();
        mBookRenewAdapter.setEmptyView(R.layout.view_empty);
        mBookRenewAdapter.setNewInstance(mBookList);
        SystemTTS.getInstance().playText("请选择图书，并点击续借");
    }

    private void showRenew() {
        if (getActivity() != null && !mSelectedMap.isEmpty()) {
            if (mDialog == null) {
                mDialog = new CommonDialog(getActivity()).loading(getString(R.string.text_loading_renew_book));
                mDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                    @Override
                    public void onDismiss(DialogInterface dialog) {
                        if (mCountDownView != null) {
                            mCountDownView.resume();
                        }
                    }
                });
            }
            mDialog.loading(getString(R.string.text_loading_renew_book));
            mDialog.show();
            if (mCountDownView != null) {
                mCountDownView.pause();
            }
            SystemTTS.getInstance().playText("正在续借");
            renewBooks();
        } else {
            SystemTTS.getInstance().playText("请先选择图书");
        }
    }

    private void renewBooks() {
        if (mDownLatch == null) {
            mDownLatch = new CountDownLatch(mSelectedMap.size());
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    mDownLatch.await();
                    //todo 写RFID标志位
                    renewFinish();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
        for (String bookBarCode : mSelectedMap.keySet()) {
            RxHttp.get(Url.renewBooks)
                    .add("ReaderBarcode", mCardNo)
                    .add("BookBarcode", bookBarCode)
                    .asString()
                    .to(RxLife.toMain(this))
                    .subscribe(new Consumer<String>() {
                        @Override
                        public void accept(String result) throws Throwable {
                            Gson gson = new Gson();
                            BorrowResult borrowResult = gson.fromJson(result, BorrowResult.class);
                            BorrowBookInfo info = mSelectedMap.get(bookBarCode);
                            if (info != null) {
                                info.setBackFlag(borrowResult.getBackFlag());
                                info.setBackInfor(borrowResult.getBackInfor());
                            }
                            mDownLatch.countDown();
                        }
                    }, new Consumer<Throwable>() {
                        @Override
                        public void accept(Throwable throwable) throws Throwable {
                            BorrowBookInfo info = mSelectedMap.get(bookBarCode);
                            if (info != null) {
                                info.setBackFlag("N");
                                info.setBackInfor("续借失败");
                            }
                            mDownLatch.countDown();
                        }
                    });
        }
    }

    private void renewFinish() {
        if (mSelectedMap != null && getActivity() != null) {
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (mDialog != null && mDialog.isShowing()) {
                        mDialog.dismiss();
                    }
                }
            });
            ArrayList<BorrowBookInfo> list = new ArrayList<>(mSelectedMap.values());
            startWithPop(RenewCompleteDelegate.getInstance(mCardNo, list));
        }
    }

    private void checkAll(boolean isCheck) {
        mSelectedMap.clear();
        List<BorrowBookInfo> list = mBookRenewAdapter.getData();
        for (BorrowBookInfo bookBean : list) {
            bookBean.setChecked(isCheck);
            if (isCheck) {
                mSelectedMap.put(bookBean.getBarCode(), bookBean);
            }
        }
        if (mBookRenewAdapter != null) {
            mBookRenewAdapter.notifyDataSetChanged();
        }
        checkIsAll();
    }

    private void checkIsAll() {
        if (mBookRenewAdapter != null) {
            mCbAll.setChecked(mBookRenewAdapter.getItemCount() == mSelectedMap.size());
        }
        mTvChooseCount.setText(String.format(LanguageUtils.getCurrentLocale(),
                "%s%d%s", getString(R.string.text_had_choose), mSelectedMap.size(), getString(R.string.text_book_unit)));
    }

    private void exit() {
        pop();
    }
}